﻿using LuaInterface;
using System.Collections.Generic;
using UnityEngine;

public class CAnimatorEvent : MonoBehaviour
{
	private Dictionary<string, AnimationClip> clipDic = new Dictionary<string, AnimationClip>();
	private Dictionary<string, string> events = new Dictionary<string, string>();

	void Awake()
	{
		var animator = GetComponentInChildren<Animator>();
		var clips = animator.runtimeAnimatorController.animationClips;
		for(int i = 0; i < clips.Length; i++)
		{
			var clip = clips[i];
			clipDic[clip.name] = clip;
		}
	}

	public void AddEvent(string animName,string eventId,string eventValue,float time)
	{
		var parameter = animName + "," + eventId;
		events[parameter] = eventValue;
		if (clipDic.TryGetValue(animName,out var clip)){
			var evts = clip.events;
			for(int i = 0; i < evts.Length; i++)
			{
				if (evts[i].stringParameter == parameter)
					return;
			}
			var evt = new AnimationEvent();
			evt.time = time;
			evt.stringParameter = parameter;
			evt.functionName = "SkillAnimationEvent";
			clip.AddEvent(evt);
		}
	}
	public void RemoveEvent(string animName,string eventId)
	{
		var parameter = animName + "," + eventId;
		events.Remove(parameter);
	}
	[NoToLua]
	public void SkillAnimationEvent(string param)
	{
		var entity = GetComponentInParent<CEntity>();
		if (entity)
		{
			if(events.TryGetValue(param,out var value))
			{
				entity.SkillAnimationEvent(param.Split(',')[1], value);
			}
		}
	}
}
